import time
import sys
sys.path.insert(0,'/Users/yangjiankun/Documents/python_review/web_serve_easy')
# from application.url import dict_router
from application.func import dict_router
def parse(recv_data):
    loc = recv_data.find('\r\n')
    request_line = recv_data[:loc]
    request_line_list = request_line.split(' ')
    request_path = request_line_list[1]
    return request_path

def application(new_socket, ip_port):

    recv_data = new_socket.recv(1024).decode()
    if not recv_data:
        print("%s已下线" % str(ip_port))
        new_socket.close()
        return

    request_path = parse(recv_data)
    response_body = ""

    response_line = "HTTP/1.1 200 OK\r\n"
    response_header = "Server:JianKun\r\n"
    response_blank = "\r\n"

    if request_path == '/':
        request_path = 'index.html'
    elif request_path.endswith('.py'):
        if request_path in dict_router:
            response_body = dict_router[request_path]().encode()
        else:
            response_line = "HTTP/1.1 404 NOTFOND\r\n"
            response_body = ('not').encode()
    
    else:
        try:
            with open("/Users/yangjiankun/Documents/python_review/web_serve_easy/static/"+request_path, 'rb') as file:
                response_body = file.read()
        except Exception as e:
            response_line = "HTTP/1.1 404 NOTFOND\r\n"
            response_body = ("%s" %e).encode()

    response = (response_line + response_header + response_blank).encode() + response_body
    new_socket.send(response) 